package cc.sunwl.security.service.impl;

import org.hibernate.Hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cc.sunwl.security.entity.SysUser;
import cc.sunwl.security.repository.UserRepository;
import cc.sunwl.security.service.UserService;
import cc.sunwl.security.vo.ActiveUser;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	private final static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	@Autowired
	private UserRepository userRepository;

	@Transactional(readOnly = true)
	@Override
	public SysUser findByUsername(String username) {
		SysUser user = userRepository.findByUsername(username);
		return user;
	}

	@Transactional(readOnly = true)
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user = this.findByUsername(username);
		if (user == null) {
			log.error("用户没有找到！！！！");
			throw new UsernameNotFoundException(String.format("User with username=%s was not found", username));
		}
		log.info("用户名： {}", user.getUsername());
		Hibernate.initialize(user.getRoles());
		ActiveUser aUser = new ActiveUser(user, user.getRoles());
		return aUser;
	}

}
